﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Design;
using System.Reflection;
using System.Windows.Forms;
using System.Windows.Forms.Design;

namespace Marmat.Forms
{
    public class RequiredComponentUITypeEditor : UITypeEditor
    {
        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.DropDown;
        }

        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            IWindowsFormsEditorService edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
            if (edSvc is object)
            {
                var source = new List<string>(new string[] { "Text", "Value", "EditValue" });
                var items = new List<string>();
                var listBox = new ListBox();
                listBox.BorderStyle = BorderStyle.None;
                foreach (MemberInfo member in context.Instance.GetType().GetMembers())
                {
                    if (member is FieldInfo || member is PropertyInfo)
                    {
                        if (source.Contains(member.Name) && !items.Contains(member.Name))
                        {
                            items.Add(member.Name);
                        }
                    }
                }

                listBox.Items.AddRange(items.ToArray());
                listBox.SelectedItem = value;
                listBox.Click += (sender, e) =>
                {
                    value = listBox.SelectedItem;
                    edSvc.CloseDropDown();
                };
                edSvc.DropDownControl(listBox);
            }

            return value;
        }
    }
}